package weaver.interfaces.zhlx.duss.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2023年11月13日 11:48
 */
public class PmsUtil {

    private static  JSONObject propVal = PropUtil.getPropVal("zhlxpms");
    private static  String URL = propVal.getString("url")+"/ECSAP2PMS";

    /**
     * 请求处理器
     *
     * @param paramsJson
     * @param dataMap
     * @return
     */
    public static JSONObject handleOKHttpRequest(JSONObject paramsJson, Map<String, Object> dataMap) {
        JSONObject resultJson = sendOKHttpRequest(paramsJson);
        dataMap.put("jkqqcs", paramsJson);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap);
        return resultJson;
    }

    private static JSONObject sendOKHttpRequest(JSONObject params) {
        JSONObject resultJson = new JSONObject();
        String code = "failure";
        String message = "";
        String data = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());
            Request request = new Request.Builder()
                    .url(URL)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 获取节点名称
     */
    public static JSONObject getNodebaseNodename(int nodeid) {
        RecordSet rs = new RecordSet();
        JSONObject json = new JSONObject();
        rs.executeQuery("select isstart,nodename,isend from workflow_nodebase where id=?", nodeid);
        rs.next();
        json.put("isstart", Util.null2String(rs.getString("isstart")));
        json.put("nodename", Util.null2String(rs.getString("nodename")));
        json.put("isend", Util.null2String(rs.getString("isend")));
        return json;
    }


    /**
     * 去掉html的标签
     *
     * @param str
     * @return
     */
    public static String removeHTMLTags(String str) {
        return str.replaceAll("\\<.*?\\>", "");
    }

    /**
     * 插入接口日志
     *
     * @param dataMap
     */
    private static void insertApiLog(Map<String, Object> dataMap) {
        String fullDate = DateUtil.getFullDate();
        try {
            InetAddress address = InetAddress.getLocalHost();
            String serverIp = address.getHostAddress();
            dataMap.put("fwqdz", serverIp);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        dataMap.put("jkqqdz", URL);
        dataMap.put("jkdysj", fullDate);
        dataMap.put("jktgf", "PMS");
        insertModelData("uf_apilog", 1, dataMap);
    }

    //建模权限重构
    private static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    private static int insertModelData(String tablename, int userid, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            String sql = "select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename=?";
            rs.executeQuery(sql, tablename);
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
            if (rs.executeUpdate(insSql, params)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        rs.executeUpdate(updatesql);
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataid;
    }

}
